<?php
/***********************************************************
 * 文档逻辑定义
 * @作者 pcfcms <1131680521@qq.com>
 * @版权 广州市春风科技有限公司
 * @主页 http://www.pcfcms.com
 * @时间 2019年12月21日
***********************************************************/
namespace app\admin\logic;

use think\facade\Db;
use think\facade\Request;
use app\admin\model\Archives;
use app\admin\model\Article;
use app\admin\model\Single;
class ArchivesLogic 
{
    // 删除文档
    public function del($del_id = array(), $thorough = 0)
    {
        $result = ['code' => 0,'msg' => '失败','data' => '','url'=>''];
        if (empty($del_id)) {
            $del_id = input('del_id/a');
        }
        if (empty($thorough)) {
            $thorough = input('thorough/d');
        }
        $id_arr = eyIntval($del_id);
        if(!empty($id_arr)){
            // 分离并组合相同模型下的文档ID
            $row = Db::name('archives')
                ->alias('a')
                ->field('a.channel,a.aid,b.table,b.ctl_name,b.ifsystem')
                ->join('channel_type b', 'a.channel = b.id', 'LEFT')
                ->where('a.aid','IN', $id_arr)
                ->select()->toArray();
            $data = array();
            foreach ($row as $key => $val) {
                $data[$val['channel']]['aid'][] = $val['aid'];
                $data[$val['channel']]['table'] = $val['table'];
                if (empty($val['ifsystem'])) {
                    $ctl_name = 'Custom';
                } else {
                    $ctl_name = $val['ctl_name'];
                }
                $data[$val['channel']]['ctl_name'] = $ctl_name;
                $data[$val['channel']]['ifsystem'] = $val['ifsystem'];
            }
            // 直接删除，跳过回收站
            if (1 == $thorough) {
                $err = 0;
                foreach ($data as $key => $val) {
                    $r = Db::name('archives')->where('aid','IN',$val['aid'])->delete();
                    if ($r) {
                        if (!empty($val['ifsystem']) && $val['ifsystem'] > 0) {
                            if($val['ctl_name'] = 'Article'){
                               $modelsystem = new Article(); // 文章系统
                            }else if($val['ctl_name'] = 'Single'){
                               $modelsystem = new Single(); // 单页系统
                            }
                            $modelsystem->afterDel($val['aid'], $val['table']);
                        } else if($val['ctl_name'] = 'Custom') {
                            $modelcustom = new \app\admin\model\Custom;
                            $modelcustom->afterDel($val['aid'], $val['table']);
                        }
                    } else {
                        $err++;
                    }
                }
            } else {
                $err = 0;
                foreach ($data as $key => $val) {
                    $r = Db::name('archives')->where('aid','IN',$val['aid'])->update(['is_del' => 1,'update_time'=>getTime(),'del_method'=>1]);
                    if ($r) {
                        //todo
                    }else{
                        $err++;
                    }
                }
            }
            if (0 == $err) {
                $result['code'] = 1;
                $result['msg']    = "删除成功";
                return $result;
            } else if ($err < count($data)) {
                $result['code'] = 1;
                $result['msg']    = "删除部分成功";
                return $result;
            } else {
                $result['code'] = 0;
                $result['msg'] = "删除失败";
                return $result;
            }
        }else{
            $result['code'] = 0;
            $result['msg'] = "文档不存在";
            return $result;
        }
    }

    // 复制文档
    public function batch_copy($aids = [], $typeid, $channel, $num = 1)
    {
        $result = ['status' => false,'msg' => '失败','data' => '','url'=>''];
        // 获取复制栏目的模型ID
        $channeltypeRow = Db::name('channel_type')->field('table')->where('id', $channel)->find();
        if (!empty($channeltypeRow)) {
            // 主表数据
            $archivesRow = Db::name('archives')->where('aid','IN', $aids)->select()->toArray(); 
            // 内容扩展表数据
            $tableExt = $channeltypeRow['table']."_content";
            $contentRow = Db::name($tableExt)->where('aid','IN', $aids)->column('*', 'aid');
            foreach ($contentRow as $kk => $vv) {
                unset($contentRow[$vv['aid']]['id']);
            }
            foreach ($archivesRow as $key => $val) {
                // 同步数据
                $archivesData = [];
                for ($i = 0; $i < $num; $i++) {
                    // 主表
                    $archivesInfo = $val;
                    unset($archivesInfo['aid']);
                    $archivesInfo['typeid'] = $typeid;
                    $archivesInfo['add_time'] = getTime();
                    $archivesInfo['update_time'] = getTime();
                    $archivesData[] = $archivesInfo;
                }

                if (!empty($archivesData)) {
                    $rdata = Db::name('Archives')->insertAll($archivesData);
                    $testres = Db::name('Archives')->getLastInsID();
                    $ppparr = array();
                    for ($i=0; $i<$rdata; $i++) { 
                        $ppparr[] = (int)$testres++;
                    }


                    if ($ppparr) {
                        // 内容扩展表的数据
                        $contentData = [];
                        $contentInfo = $contentRow[$val['aid']];
                        // 需要复制的数据与新产生的文档ID进行关联
                        foreach ($ppparr as $k1 => $v1) {
                            $aid_new = $v1;
                            // 内容扩展表的数据
                            $contentInfo['aid'] = $aid_new;
                            $contentData[] = $contentInfo;
                        }
                        // 批量写入内容扩展表
                        if (!empty($contentData)) {
                            Db::name($tableExt)->insertAll($contentData);
                        }
                    }
                    else {
                        $result['status'] = false;
                        $result['msg']    = "复制失败！";
                        return $result;
                    }
                }
            }
            $result['status'] = true;
            $result['msg']    = "复制成功！";
            return $result;
        } else {
            $result['status'] = false;
            $result['msg']    = "模型不存在！";
            return $result;
        }
    }

    // 获取文档模板文件列表 小潘 by 2020.03.08
    public function getTemplateList($nid = 'article')
    {
        $gzpcfglobal = get_global();
        $tpl_theme = $gzpcfglobal['admin_config']['tpl_theme'];
        $planPath = "template/{$tpl_theme}/pc";
        $dirRes   = opendir($planPath);
        $view_suffix = config('view.view_suffix');
        // 模板PC目录文件列表
        $templateArr = array();
        while($filename = readdir($dirRes)){
            if (in_array($filename, array('.','..'))) {
                continue;
            }
            array_push($templateArr, $filename);
        }
        $templateList = array();
        foreach ($templateArr as $k2 => $v2) {
            $v2 = iconv('GB2312', 'UTF-8', $v2);
            preg_match('/^(view)_'.$nid.'(_(.*))?\.'.$view_suffix.'/i', $v2, $matches1);
            if (!empty($matches1)) {
                if ('view' == $matches1[1]) {
                    array_push($templateList, $v2);
                }
            }
        }
        return $templateList;
    }

}
